<template>
    <div>
        <!-- 操作按钮 -->
        <div class="operatBtnWrapper">
            <button class="operatBtn marR5" @click.stop="beforeSubmit"  v-if=" isLocked !== 2">准备提交</button>
            <!-- <button class="operatBtn marR5" @click.stop="submit"  :class="{notAllowed:!checked && form.declareMethod === 3}" :disabled="!checked && form.declareMethod === 3" v-if=" isLocked !== 2">确认提交</button> -->
            <button class="operatBtn marR5" type="reset" @click.stop="resetForm('form')" v-if=" isLocked !== 2">重置内容</button>
            <span class="lightGrayColor">申报方式</span>
            <el-select v-model="form.declareMethod" placeholder="请选择申报方式" class="inputTxtWrapper" :disabled="isLocked === 2">
                <el-option key = 1 label = "无须申报" :value="1">无须申报</el-option>
                <el-option key = 2 label = "自主申报" :value="2">自主申报</el-option>
                <el-option key = 3 label = "公司代扣" :value="3">公司代扣</el-option>
            </el-select>
        </div>

        <div class="grayLine marLR20" v-if=" isLocked !== 2"></div>

        <!-- 表单 -->
		<el-form ref="form" :model="form" :rules="rules" class="paddLR20 marT10" :inline="true" hide-required-asterisk=true label-width="82px" :disabled="isLocked === 2">
            <el-row>
                <el-col :span="24">
                    <el-form-item label="境外人员" prop="isSeasPerson" title="境外人员">
                        <el-radio v-model="form.isSeasPerson" :label = 1>是</el-radio>
                        <el-radio v-model="form.isSeasPerson" :label = 2>否</el-radio>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row v-if="form.declareMethod === 3">
                <el-col :span="8">
                    <el-form-item label="子女教育" prop="childEduQuota" title="子女教育额度">
                        <el-input v-model.trim.number="form.childEduQuota" placeholder="请输入子女教育额度" maxlength='10' class="inputTxtWrapper"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="继续教育" prop="continueEduQuota" title="继续教育额度">
                        <el-input v-model.trim.number="form.continueEduQuota" placeholder="请输入继续教育额度" maxlength='10' class="inputTxtWrapper"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="赡养老人" prop="supportElderQuota" title="赡养老人额度">
                        <el-input v-model.trim.number="form.supportElderQuota" placeholder="请输入赡养老人额度" maxlength='10' class="inputTxtWrapper"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="租房/购房" prop="houseRent" title="租房/购房">
                        <el-input v-model.trim.number="form.houseRent" placeholder="请输入租房/购房金额" maxlength='6' class="inputTxtWrapper"></el-input>
                    </el-form-item>
                </el-col>

                <el-col :span="8" v-if="form.houseRent !== ''">
                    <el-form-item label="省" prop="provinceCode">
                    <el-select v-model="form.provinceCode" placeholder="请选择省" class="inputTxtWrapper"  @change="changeByProvince(null,null)">
                        <el-option
                            v-for="item in provList"
                            :key="item.provCode"
                            :label="item.provName"
                            :value="item.provCode">
                            </el-option>
                    </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8" v-if="form.houseRent !== ''">
                    <el-form-item label="市" prop="cityCode">
                         <el-select v-model="form.cityCode" placeholder="请选择市" class="inputTxtWrapper"  @change="changeByCity">
                            <el-option
                                v-for="item in cityList"
                                :key="item.cityCode"
                                :label="item.cityName"
                                :value="item.cityCode">
                            </el-option>
                         </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8" v-if="form.houseRent !== ''">
                    <el-form-item label="区(县)" prop="districtCode">
                        <el-select v-model="form.districtCode" placeholder="请选择区(县)" class="inputTxtWrapper">
                            <el-option
                                v-for="item in regionList"
                                :key="item.regionCode"
                                :label="item.regionName"
                                :value="item.regionCode">
                            </el-option>
                         </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8" v-if="form.houseRent !== ''">
                    <el-form-item label="街道地址" prop="street">
                        <el-input v-model.trim = "form.street" placeholder="请输入街道地址" maxlength='50' class="inputTxtWrapper"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8" v-if="form.houseRent !== ''">
                    <el-form-item label="详细地址" prop="detailAddress">
                        <el-input v-model.trim="form.detailAddress" placeholder="请输入详细地址" maxlength='50' class="inputTxtWrapper"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8" v-if="form.houseRent !== ''">
                    <el-form-item  label="是否租房" prop="isRentHouse">
                        <el-radio v-model="form.isRentHouse" :label = 1>租房</el-radio>
                        <el-radio v-model="form.isRentHouse" :label = 2>购房</el-radio>
                    </el-form-item>
                </el-col>
                <!-- <el-col :span="24">
                    <p class="tipNoData">
                        <el-checkbox v-model="checked">
                            <span class="red">请员工确保信息填写无误，如有变更，及时修改提交并告知行政部，以上信息本公司系统只负责采集汇总，员工自行对接个税系统申报，并对以上信息的准确性自行负责。</span>
                        </el-checkbox>
                    </p>
                </el-col> -->
            </el-row>
		</el-form>

        <!--  -->
        <div class="cropperWrapper alphaBlack" v-if="isShowMask">
            <div class="posFixedCenter">
                <div>
                    <el-checkbox class="resetCheckFont" v-model="checked">
                        请员工确保信息填写无误，如有变更，及时修改提交并告知行政部，以上信息本公司系统只负责采集汇总，员工自行对接个税系统申报，并对以上信息的准确性自行负责。
                    </el-checkbox>
                </div>
                <div class="marT20">
                    <button class="operatBtn marR5" :class="{notAllowed : !checked}" @click.stop="submit">确认提交</button>
                    <button class="operatBtn marR5" @click.stop="isShowMask  = false">取消</button>
                    <!-- <button class="operatBtn" @click.stop="returnBack">返回上一页</button> -->
                </div>
            </div>
        </div>

    </div>
</template>

<script>
import http from '../../../../assets/js/http'
import _g from '@/assets/js/global'
import Cookies from "js-cookie"

import { ADDRLIST } from "@/assets/js/data.js"
import {validateNonnegativeNum} from "@/assets/js/common.js"

export default {

    data() {
         // 非负数验证
        let validateNonNum =  (rule, value, callback) => {
            if (value !== '' && !validateNonnegativeNum(value)) {
                callback(new Error("请输入非负数"))
            }else{
                callback()
            }
        }

        return{
            isShowMask:false,// 默认隐藏遮罩
            isLocked:1,//   默认可以提交
            checked : false,//  告知信息默认不选中

            provList : [],//    省
            cityList : [],//    市
            regionList : [],//    区县

            userId : null,//所属用户id
            sixItemId : null,//申报六项id

            form: {
                declareMethod : 1,//申报方式.1无，2自主申报，3公司代扣(需要填写相关信息)
                isSeasPerson : 2,//是否境外人员 1:是,2:否
                provinceCode : null,//省code
                provinceName : '',//省名字
                cityCode : null,//市code
                cityName : '',//市名字
                districtCode : null,//区(县)code
                districtName : '',//区(县)名字
                street : '',//街道
                detailAddress : '',//详细地址
                childEduQuota : '',//子女教育额度
                continueEduQuota : '',//继续教育额度
                supportElderQuota : '',//赡养老人额度
                houseRent : '',//租房/购房额度
                isRentHouse :null,//   1租房2购房
            },
            rules:{
                childEduQuota : [{validator: validateNonNum,message: "请输入非负数",trigger: "change"}],
                continueEduQuota : [{validator: validateNonNum,message: "请输入非负数",trigger: "change"}],
                supportElderQuota : [{validator: validateNonNum,message: "请输入非负数",trigger: "change"}],
                houseRent : [{validator: validateNonNum,message: "请输入非负数",trigger: "change"}],
                street : [{required: true, message: "请输入街道地址",trigger: "change"}],
                detailAddress : [{required: true, message: "请输入详细地址",trigger: "change"}],
                isRentHouse:[{required: true, message: "请选择租房/购房类型",trigger: "change"}]
            },
        }
    },
    created () {
        this.userId = this.$route.query.userId
        // this.getProvList()
        // this.changeByProvince()
        this.querySixItemByUserId()
    },
    methods: {
        /* 返回上一页 */
        // returnBack(){
        //     const that = this
        //      that.$confirm('离开页面之后，信息将不会被保存', '是否继续', {
        //         confirmButtonText: '确定',
        //         cancelButtonText: '取消',
        //         type: 'warning',
        //         center: true
        //     }).then(() => {
        //         that.$router.go(-1)
        //     }).catch(() => {})
        // },

        /* 初始化获取省市区 */
        getProvList(provinceCode){
            let provList = []
            for(let item of ADDRLIST){
                provList.push({provName : item.name,provCode : item.code,})
            }
            if(provinceCode === null){
                provinceCode = ADDRLIST[0].code
            }
            this.form.provinceCode = parseInt(provinceCode)
            this.provList = provList
        },

        /* 省市区(县)联动 */
        changeByProvince(currCityCode,currRegionCode){
            let regionList = []
            let cityList = []
            let isFindPro = false                                               //  默认没有匹配省
            const currProvinceCode = this.form.provinceCode
            // let currCityCode = null
            // let currRegionCode = null

            for(let item of ADDRLIST){
                if(item.code == currProvinceCode){                                                       //  如果省匹配
                        isFindPro = true
                        if(currCityCode === null){
                             currCityCode =  (item.child)[0].code
                        }
                    for(let cityItem of item.child){                                                                        //  遍历市
                        cityList.push({cityName : cityItem.name,cityCode : cityItem.code})
                        if(cityItem.code == currCityCode){                                                            //  如果市匹配
                                    if(currRegionCode === null){
                                        currRegionCode = (cityItem.child)[0].code
                                    }
                                for(let regionItem of cityItem.child){                                                                                                              //  遍历区县
                                    regionList.push({regionName : regionItem.name,regionCode : regionItem.code})
                                }
                            }
                    }
                    if(isFindPro){
                        break
                    }
                }
            }
            this.cityList = cityList
            this.regionList = regionList
            this.form.cityCode = currCityCode
            this.form.districtCode = currRegionCode
        },
        /* 市区(县)联动 */
        changeByCity(){
            let regionList = []
            let isFindPro = false                                               //  默认没有匹配省
            let isFindCity = false                                               //  默认没有匹配市
            const currProvinceCode = this.form.provinceCode
            const currCityCode = this.form.cityCode
            let currRegionCode = null
            for(let item of ADDRLIST){
                if(item.code == currProvinceCode){                                                       //  如果省匹配
                    isFindPro = true
                    for(let cityItem of item.child){                                                                        //  遍历市
                        if(cityItem.code == currCityCode){                                                            //  如果市匹配
                                currRegionCode = (cityItem.child)[0].code
                                for(let regionItem of cityItem.child){                                                                                                              //  遍历区县
                                    regionList.push({regionName : regionItem.name,regionCode : regionItem.code})
                                }
                        }
                        if(isFindCity){
                            break
                        }
                    }
                    if(isFindPro){
                        break
                    }
                }
            }
            this.regionList = regionList
            this.form.districtCode = currRegionCode
        },
        /* 根据用户id查询申报六项扣除 */
        querySixItemByUserId(){
            const that = this
            let userId = that.userId

            _g.showLoading('加载中');
             that.apiPost('admin/sixitem/querySixItemByUserId',{userId}).then((res) => {
                _g.showLoading().close()
                if(typeof res === 'string'){
                    res = JSON.parse(res)
                }
                if (res.code != 200) {
                    that.handleError(res)
                } else {
                    if(res.data.isSuccess === 0){
                        if(res.data.sixItemList !== null){
                            that.sixItemId = res.data.sixItemList.id
                            that.form.declareMethod = res.data.sixItemList.declare_method                            
                            that.form.isSeasPerson = res.data.sixItemList.is_seas_person   

                            that.getProvList(res.data.sixItemList.province_code)
                            that.changeByProvince(res.data.sixItemList.city_code,res.data.sixItemList.district_code)

                            that.form.street = res.data.sixItemList.street !== null ? res.data.sixItemList.street : ''                            
                            that.form.detailAddress = res.data.sixItemList.detail_address !== null ? res.data.sixItemList.detail_address : ''                            
                            that.form.childEduQuota = res.data.sixItemList.child_edu_quota !== null ? res.data.sixItemList.child_edu_quota : ''                            
                            that.form.continueEduQuota = res.data.sixItemList.continue_edu_quota !== null ? res.data.sixItemList.continue_edu_quota : ''                             
                            that.form.supportElderQuota = res.data.sixItemList.support_elder_quota !== null ? res.data.sixItemList.support_elder_quota : ''                            
                            that.form.houseRent = res.data.sixItemList.house_rent !== null ? res.data.sixItemList.house_rent : ''                            
                            that.form.isRentHouse = res.data.sixItemList.is_rent_house          
                            
                            if(res.data.sixItemList.declare_method === 3){                          //  如果为公司代扣申报方式
                                //  遍历省列表，找出对应省的名字
                                for(let proItem of that.provList){
                                    if(proItem.provCode == res.data.sixItemList.province_code){
                                        that.form.provinceName = proItem.provName
                                        break
                                    }
                                }
                                
                                //  遍历市列表，找出对应市的名字
                                for(let cityItem of that.cityList){
                                    if(cityItem.cityCode === res.data.sixItemList.city_code){
                                        that.form.cityName = cityItem.cityName
                                        break
                                    }
                                }

                                //  遍历区(县)列表，找出对应区(县)的名字
                                for(let regionItem of that.regionList){
                                    if(regionItem.regionCode === res.data.sixItemList.district_code){
                                        that.form.districtName = regionItem.regionName
                                        break
                                    }
                                }
                            }
                            that.isLocked = res.data.sixItemList.is_modified
                        }else{
                            that.getProvList(null)
                            that.changeByProvince(null,null)
                        }
                        
                    }else if(res.data.isSuccess === 1){
                        _g.toastMsg("error", res.message)
                    }
                }
            })
        },
         /* 重置表单 */
        resetForm() {
            this.$refs.form.resetFields();
        },
        /* 提交表单之前 */
        beforeSubmit(){
            let declareMethod = this.form.declareMethod
            let childEduQuota = this.form.childEduQuota
            let continueEduQuota = this.form.continueEduQuota
            let supportElderQuota = this.form.supportElderQuota
            let houseRent = this.form.houseRent
            

            if(declareMethod === 3){                                                //  如果为公司代扣
                if(childEduQuota === '' && continueEduQuota === '' && supportElderQuota === '' && houseRent === ''){
                    _g.toastMsg("warning", '子女教育额度,继续教育额度,赡养老人额度,租房/购房，至少填写一个!')
                    return
                }
            }
            
            this.$refs.form.validate((valid) => {   //  如果表单校验通过
                if(valid){
                    this.isShowMask = true
                }
            })
        },
        /* 提交表单 */
        submit(){
            const that = this
             const sixItemId = that.sixItemId
             let declareMethod = that.form.declareMethod
             let isSeasPerson = that.form.isSeasPerson
             const userId = that.userId

            let provinceCode = that.form.provinceCode
            let cityCode = that.form.cityCode
            let districtCode = that.form.districtCode
            let street = that.form.street
            let detailAddress = that.form.detailAddress
            let childEduQuota = that.form.childEduQuota
            let continueEduQuota = that.form.continueEduQuota
            let supportElderQuota = that.form.supportElderQuota
            let houseRent = that.form.houseRent


            let data = {
                sixItemId,
                declareMethod,
                isSeasPerson,
                userId
            }

            let requestUrl = ''
            if(sixItemId === null){                                                     //  初次新增
                requestUrl = 'admin/sixitem/addSixItem'
            }else{                                                                                  //  修改
                requestUrl = 'admin/sixitem/updateSixItem'
            }

            if(declareMethod === 3){                                                //  如果为公司代扣
                //  if(childEduQuota === '' && continueEduQuota === '' && supportElderQuota === '' && houseRent === ''){
                //     _g.toastMsg("warning", '子女教育额度,继续教育额度,赡养老人额度,租房/购房，至少填写一个!')
                //     return
                // }

                data.childEduQuota = that.form.childEduQuota
                data.continueEduQuota = that.form.continueEduQuota
                data.supportElderQuota = that.form.supportElderQuota
                data.remarks = that.form.remarks

                if(houseRent !== ''){
                    data.provinceCode = that.form.provinceCode
                    data.cityCode = that.form.cityCode
                    data.districtCode = that.form.districtCode
                    data.street = that.form.street
                    data.detailAddress = that.form.detailAddress
                    data.houseRent = that.form.houseRent
                    data.isRentHouse = that.form.isRentHouse
                }

                // this.$refs.form.validate((valid) => {
                //     if (valid) {
                        that.$confirm('是否确认提交?', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning',
                            center: true
                        }).then(() => {
                                _g.showLoading('提交中')
                                that.apiPost(requestUrl, data).then((res) => {
                                    _g.showLoading().close()
                                    if(typeof res === 'string'){
                                        res = JSON.parse(res)
                                    }
                                    if (res.code != 200) {
                                    that.handleError(res)
                                    } else {
                                        if(res.data.isSuccess === 0){             //  成功
                                                _g.toastMsg("success", res.message)
                                                that.isLocked = 2
                                                // that.$router.push('/admin/users/list')
                                                // that.$router.go(-1)
                                                that.isShowMask = false//   隐藏遮罩
                                            }else if(res.data.isSuccess === 1){
                                                _g.toastMsg("error", res.message)
                                            }else if(res.data.isSuccess === 2){
                                                _g.toastMsg("warning", res.message)
                                                that.$router.push('/admin/users/list')
                                            }
                                    }
                                })
                        }).catch(() => {})
                //     }
                // })
            }else{                                                                          //  如果为无须申报或自主申报
                 that.$confirm('是否确认提交?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                    center: true
                }).then(() => {
                        _g.showLoading('提交中')
                        that.apiPost(requestUrl, data).then((res) => {
                            _g.showLoading().close()
                            if(typeof res === 'string'){
                                res = JSON.parse(res)
                            }
                            if (res.code != 200) {
                            that.handleError(res)
                            } else {
                                if(res.data.isSuccess === 0){             //  成功
                                    _g.toastMsg("success", res.message)
                                    that.$router.go(-1)
                                    // that.$router.push('/admin/users/list')
                                }else if(res.data.isSuccess === 1){
                                    _g.toastMsg("error", res.message)
                                }else if(res.data.isSuccess === 2){
                                    _g.toastMsg("warning", res.message)
                                    that.$router.go(-1)
                                    // that.$router.push('/admin/users/list')
                                }
                            }
                        })
                }).catch(() => {})
            }
        }
    },
    mixins: [http]
}
</script>

